package com.binarycube.webserver.authenticator;

import java.util.HashMap;
import java.util.Map;

import com.binarycube.webserver.config.AuthenticatorConfig;
import com.binarycube.webserver.wrappers.WrappedRequest;

public class SimpleAuthenticator implements IAuthenticator {

	Map<String, String> users;
	AuthenticatorConfig authenticatorConfig;
	
	@Override
	public boolean authenticate(WrappedRequest request) {
		 String username = request.getParameter(authenticatorConfig.getUsernameField());
	     String password = request.getParameter(authenticatorConfig.getPasswordField());
	     if (username == null) return false;
	     //Do we have this user ?
	     if (users.containsKey(username)) {
	    	 String pword = users.get(username);
	    	 //Passwords match ?
	    	 if (password.equals(pword)) return true;
	     }
	    //Otherwise failed 
		return false;
	}

	@Override
	public void configure(AuthenticatorConfig config) {
		authenticatorConfig = config;
		//Load the user list from the config file, and persist in memory
		users = new HashMap<String, String>();
		String[] lines = config.getProperty("users").trim().split("\n");
		for (String line: lines) {
			String[] tmp = line.split(":");
			users.put(tmp[0], tmp[1]);
		}
		
		

	}

	@Override
	public String getUID(WrappedRequest wrappedRequest) {
		return wrappedRequest.getParameter(authenticatorConfig.getUsernameField());
	}




}
